package com.jspx.txweb.action;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.jspx.boot.environment.Environment;
import com.jspx.json.JSONObject;
import com.jspx.sioc.annotation.Ref;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Operate;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.dao.MemberDAO;
import com.jspx.txweb.env.TXWeb;
import com.jspx.txweb.env.TXWebIoc;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.txweb.table.SmsSendLog;
import com.jspx.utils.RandomUtil;
import com.jspx.utils.StringUtil;

@HttpMethod(caption = "阿里云短信")
public class AliySmsValidAction extends ActionSupport {
    protected MemberDAO memberDAO;
    @Ref(name = TXWebIoc.memberDAO, namespace = TXWebIoc.userNamespace)
    public void setMemberDAO(MemberDAO memberDAO) {
        this.memberDAO = memberDAO;
    }

    private String accessKeyId = StringUtil.empty;
    private String secret = StringUtil.empty;
    //"贵州佰分之一摩都电子商务"
    private String signName = StringUtil.empty;

    // 验证码字符个数
    private int codeCount = 0;
    private String regionId = StringUtil.empty;
    private String templateCode = StringUtil.empty;


    /**
     *
     * @param accessKeyId 阿里云 accessKeyId
     */
    @Safety(request = false)
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    @Safety(min = 3,max = 10,request = false)
    public void setCodeCount(int codeCount) {
        this.codeCount = codeCount;
    }
    /**
     *
     * @param secret  阿里云 secret
     */
    @Safety(request = false)
    public void setSecret(String secret) {
        this.secret = secret;
    }

    /**
     *
     * @param signName 阿里云 短信模板签名
     */
    @Safety(request = false)
    public void setSignName(String signName) {
        this.signName = signName;
    }


    @Safety(request = false)
    public void setRegionId(String regionId) {
        this.regionId = regionId;
    }

    @Safety(request = false)
    public void setTemplateCode(String templateCode) {
        this.templateCode = templateCode;
    }


    private void loadConfig()
    {
        //为了兼容手动配置 begin
        if (StringUtil.isNULL(accessKeyId))
            accessKeyId = config.getString("aliySmsAccessKeyId");

        if (StringUtil.isNULL(secret))
            secret = StringUtil.trim(config.getString("aliySmsSecret"));

        if (StringUtil.isNULL(signName))
            signName = StringUtil.trim(config.getString("aliySmsSignName"));

        if (StringUtil.isNULL(regionId))
            regionId = StringUtil.trim(config.getString("aliySmsRegionId"));

        if (codeCount<=2)
            codeCount = config.getInt("aliySmsCodeCount",5);
        //为了兼容手动配置 end
    }

    //发送到那个手机号
    private String phoneNumbers = StringUtil.empty;
    @Safety(min = 5,max = 15)
    public void setPhoneNumbers(String phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

    @Operate(caption = "登录验证")
    public void sendLoginValid() {
        loadConfig();
        //登录确认验证码, 不动
        if (StringUtil.isNULL(templateCode))
            templateCode = config.getString("aliySmsLoginValidTemplateCode");
        send();
    }

    @Operate(caption = "注册验证")
    public void sendRegValid() {
        loadConfig();
        //登录确认验证码, 不动
        if (StringUtil.isNULL(templateCode))
            templateCode = config.getString("aliySmsRegValidTemplateCode");
        send();
    }

    @Operate(caption = "身份验证")
    public void sendIdentityValid() {

        loadConfig();
        //登录确认验证码, 不动
        if (StringUtil.isNULL(templateCode))
            templateCode = config.getString("aliySmsIdentityTemplateCode");
        send();
    }

    @Operate(caption = "变更验证")
    public void sendChangeValid() {
        loadConfig();
        //登录确认验证码, 不动
        if (StringUtil.isNULL(templateCode))
            templateCode = config.getString("aliySmsChangeValidTemplateCode");
        send();
    }

    private String makeCode() {
        StringBuilder randomCode = new StringBuilder();
        for (int i=0; i<this.codeCount; i++)
        {
            randomCode.append(RandomUtil.getRandomInt(0,9));
        }
        return randomCode.toString();
    }


    private void send()
    {
        if (!config.getBoolean(Environment.useSms))
        {
            addFieldInfo(Environment.warningInfo,"短信功能没有开启");
            return;
        }
        try {
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
            //这里阿里云sdk有个bug，在web方式会载入不到配置文件

            IAcsClient client = new DefaultAcsClient(profile);

            String code = makeCode();
            session.setAttribute(TXWeb.jspxSmsValidate, code);
            session.setAttribute(TXWeb.jspxSmsValidateTime, System.currentTimeMillis());

            CommonRequest request = new CommonRequest();
            //request.setProtocol(ProtocolType.HTTPS);
            request.setSysProduct("Dysmsapi");
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");
            request.setSysRegionId(regionId);
            request.putQueryParameter("PhoneNumbers", phoneNumbers);
            request.putQueryParameter("SignName", signName);
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
            CommonResponse commonResponse = client.getCommonResponse(request);
            JSONObject json = new JSONObject(commonResponse.getData());
            json.put("validateSecond", config.getInt("validateSecond",80));
            if ("OK".equalsIgnoreCase(json.getString("Code")))
            {
                addActionMessage("发送成功");
            }
            else
            {
                addFieldInfo(Environment.warningInfo,"发送失败");
            }

            SmsSendLog smsSendLog = new SmsSendLog();
            smsSendLog.setRegionId(regionId);
            smsSendLog.setPhoneNumbers(phoneNumbers);
            smsSendLog.setSignName(signName);
            smsSendLog.setTemplateCodeId(templateCode);
            smsSendLog.setTemplateValue(code);
            smsSendLog.setResultCode(json.getString("Code"));
            smsSendLog.setBizId(json.getString("BizId"));
            smsSendLog.setRequestId(json.getString("RequestId"));

            memberDAO.save(smsSendLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String execute() throws Exception {
        setActionResult(ROC);
        return super.execute();
    }

}
